<?php
class User_model extends CI_Model{
	public function is_logged_in(){
		if($this->session->userdata('admin') != NULL){
			return TRUE;
		}
		return FALSE;
	}
	
	public function validate_login(){
		$u = $this->input->post('login');
		$p = $this->input->post('password');
		
		$result = $this->db->get_where('users',array('username' => $u,'password' => md5($p),'type' => '2','public' => '1'));
		
		if($result->num_rows()){
			$this->changeIsLogged($u,1);
			$data = $result->row_array();
			$this->session->set_userdata('admin',$data['username']);
			$this->session->set_userdata('admin_name',$data['lastname'] . ' ' . $data['firstname']);
			//$this->session->set_userdata('avatar',$data['avatar']);
			$result->free_result();
			return TRUE;
		}else{
			$result->free_result();
			return FALSE;
		}
	}
	
	public function changeIsLogged($username,$param){
		$data = array('islogged' => $param);
		$this->db->where('username', $username);
		$this->db->update('users',$data);
	}
	
	public function getAdminLogged(){
		$q = $this->db->get_where('users',array('type' => '2','islogged' => '1','public' => '1'));
		
		$data = array();
		if($q->num_rows()){
			$data = $q->result_array();
		}
		
		$q->free_result();
		return $data;
	}
	
	public function register(){
		$data = array(
			'username' => 'admin1',
			'password' => md5('admin1'),
			'firstname' => 'Setven',
			'lastname' => 'Nguyen',
			'type' => '2',
			'public' => '1'
		);
		
		$this->db->insert('users',$data);
		
	}
}